﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common.Model;
using System.Collections;
using System.Net.Mail;
using System.Net;
namespace BLL
{
    public class Tools
    {
        public static StockVirtual GetStockByCode(String code)
        {
            Hashtable stockHash;
            if (globalObject.GlobalHash == null)
            {
                stockHash = new Hashtable();
                List<Common.Model.StockVirtual> Virtuals = (new BLL.Tools()).GetAll();
                if (Virtuals != null && Virtuals.Count > 0)
                {
                    foreach (Common.Model.StockVirtual virtualModel in Virtuals)
                    {
                        stockHash[virtualModel.StockCode] = virtualModel;
                    }
                    BLL.globalObject.GlobalHash = stockHash;
                }
            }
            else
            {
                stockHash = globalObject.GlobalHash;
            }
            if(stockHash.Contains(code))
            {
            StockVirtual stock =(StockVirtual) stockHash[code];
            return stock;
            }
            return null;
        }
        /// <summary>
        /// 临时从网上获得数据
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static StockVirtual GetStockByCodeInstance(String code)
        {
            Stock stockModel = new Stock();
            StockBLL stockBL = new StockBLL();
            stockModel = stockBL.GetModel(code);
            string codeString="";
            if (stockModel == null)
            {
                return null;
            }
            if (stockModel.StockType == 1)
            {
                codeString += "s_sh" + stockModel.Code.Trim() + ",";
            }
            else
            {
                codeString += "s_sz" + stockModel.Code.Trim() + ",";
            }
            String str = "http://hq.sinajs.cn/list=" + codeString.Substring(0, codeString.Length - 1);
            if (String.IsNullOrEmpty(str))
            {
                return null;
            }
            Uri uri = new Uri(str);
            System.Net.WebRequest req = System.Net.WebRequest.Create(uri);
            System.Net.WebResponse resp = req.GetResponse();
            System.IO.Stream str3 = resp.GetResponseStream();
            System.IO.StreamReader reader = new System.IO.StreamReader(str3, System.Text.Encoding.Default);
            String s = reader.ReadToEnd().Trim();
            String kon = ";";
            String[] stockString = s.Split(kon.ToCharArray());
            int n1 = stockString.Length - 1;
            StockVirtual StockList = new StockVirtual();
            for (int i = 0; i < stockString.Length - 1; i++)
            {
                String rep = "var hq_str_s_"; //"var hq_str_";
                String tri = "\"";
                stockString[i] = stockString[i].Trim().Replace(rep, "");
                stockString[i] = stockString[i].Trim().Replace(tri, "");
                stockString[i] = stockString[i].Replace("=", ",");
                String[] tempString = stockString[i].Split(',');
                StockVirtual StockModel = new StockVirtual();
                StockModel.StockCode = tempString[0].Substring(2);
                StockModel.StockName = tempString[1];
                StockModel.XianJia = decimal.Parse(tempString[2]);
                StockModel.UpDownMargin = decimal.Parse(tempString[3]);
                StockModel.UpDownCount = decimal.Parse(tempString[4]);
                StockModel.DealMoney = decimal.Parse(tempString[5]);
                StockModel.DealCount = decimal.Parse(tempString[6]);
            }
            reader.Close();
            return StockList;
        }
        public List<StockVirtual> GetAll()
        {
            String str = GetUrl();
            if (String.IsNullOrEmpty(str))
            {
                return null;
            }
            Uri uri = new Uri(str);
            System.Net.WebRequest req = System.Net.WebRequest.Create(uri);
            System.Net.WebResponse resp = req.GetResponse();
            System.IO.Stream str3 = resp.GetResponseStream();
            System.IO.StreamReader reader = new System.IO.StreamReader(str3, System.Text.Encoding.Default);
            String s = reader.ReadToEnd();
            if (String.IsNullOrEmpty(s))
            {
                return null;
            }
            String kon = ";";
            String[] stockString = s.Split(kon.ToCharArray());
            int n1 = stockString.Length - 1;
            List<StockVirtual> StockList = new List<StockVirtual>();
            for (int i = 0; i < stockString.Length - 1; i++)
            {
                String rep = "var hq_str_s_"; //"var hq_str_";
                String tri = "\"";
                stockString[i] = stockString[i].Trim().Replace(rep, "");
                stockString[i] = stockString[i].Trim().Replace(tri, "");
                stockString[i] = stockString[i].Replace("=", ",");
                String[] tempString = stockString[i].Split(',');
                StockVirtual StockModel = new StockVirtual();
                StockModel.StockCode = tempString[0].Substring(2);
                StockModel.StockName = tempString[1];
                StockModel.XianJia = decimal.Parse(tempString[2]);
                StockModel.UpDownCount = decimal.Parse(tempString[3]);
                StockModel.UpDownMargin = decimal.Parse(tempString[4]);
                StockModel.DealCount = decimal.Parse(tempString[5]);
                StockModel.DealMoney = decimal.Parse(tempString[6]);               
                StockList.Add(StockModel);
            }
            reader.Close();
            return StockList;
        }

        private string GetUrl()
        {
            List<Stock> stocks= GetCode();
            String stockString = "";
            if (stocks.Count > 0)
            {
                foreach(Stock stockModel in stocks)
                {
                    if (stockModel.StockType == 1)
                    {
                        stockString += "s_sh" + stockModel.Code.Trim() + ",";
                    }
                    else
                    {
                        stockString += "s_sz" + stockModel.Code.Trim() + ",";
                    }
                }
                String back = "http://hq.sinajs.cn/list=" +stockString.Substring(0,stockString.Length-1);
                return back;
            }
            else
            {
                return null;
            }
            //"http://hq.sinajs.cn/list=s_sz000630,s_sh600756,s_sz000809,s_sz002431,s_sh600869,s_sz002006,s_sh600735,s_sh600851,s_sz002300,s_sz002371,s_sz300092,s_sz000929,s_sh601006";
            //String back = "http://hq.sinajs.cn/list=" + stockString;
            //return back;
        }

        private List<Stock> GetCode()
        {
            List<StockAlert> stockAlerts = new List<StockAlert>();
            StockAlertBLL alertBLL = new StockAlertBLL();
            stockAlerts = alertBLL.GetUsedModelList("");
            List<Stock> StockList = new List<Stock>();
            String stockString = "00";
            foreach (StockAlert alert in stockAlerts)
            {
                stockString += ",'" + alert.Code + "' ";
            }
            StockBLL stockBL = new StockBLL();
            StockList = stockBL.GetModelList(" code in ( "+stockString+")");
            return StockList;
        }
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="toMail"></param>
        /// <param name="body"></param>
        /// <param name="subject"></param>
        /// <param name="title"></param>
        /// <returns></returns>
        public static bool SendMail(String toMail, String body, String subject, string title,Boolean isHtml )
        {
            string s_from = "liuhengbo@126.com";
            string pwd = "lhb1989415";
            string s_to = toMail;
            int i = s_from.IndexOf("@");
            string usname = s_from.Substring(0, i);
            MailAddress from;
            MailAddress to;
            if (string.IsNullOrEmpty(title))
            {
                 from = new MailAddress(s_from,"TelWo");
                 to = new MailAddress(s_to);
            }
            else
            {
                 from = new MailAddress(s_from, title);
                 to = new MailAddress(s_to, title);
            }
            MailMessage mailobj = new MailMessage(from, to);
            mailobj.Subject = subject;
            mailobj.Body = body;
            mailobj.IsBodyHtml = isHtml;
            mailobj.BodyEncoding = System.Text.Encoding.GetEncoding("gb2312");
            mailobj.Priority = MailPriority.Normal;
            SmtpClient smtp = new SmtpClient("smtp.126.com");
            smtp.UseDefaultCredentials = false;
            smtp.Credentials = new NetworkCredential(usname, pwd);
            smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
            try
            {
                smtp.Send(mailobj);
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获得一个指定范围内的随机数
        /// </summary>
        /// <param name="min">最小值</param>
        /// <param name="max">最大值</param>
        /// <returns>字符串形式的随机数</returns>
        private static string GetRandom(int min, int max)
        {
            Random r = new Random();
            int x = 0;
            do
            {
                x = r.Next(min, max);
            } while (x <= min && x >= max);
            return x.ToString();
        }
        /// <summary>
        /// 得到指定长度的随机码
        /// </summary>
        /// <param name="n">长度</param>
        /// <returns></returns>
        public static string GetRandomCode(int n)
        {
            Random rd = new Random();
            string[] source = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };
            String code = "";
            for (int i = 0; i < n; i++)
            {
                code += source[rd.Next(0, source.Length)];
            }
            return code;
        }
        /// <summary>
        /// 发送手机短信
        /// </summary>
        /// <param name="phone">手机号码</param>
        /// <param name="smsText">发送的内容</param>
        /// <returns></returns>
        public string SendPhoneCode(string phone, string smsText)
        {
            return "";//todo:未实现的发送手机短信
        }
    }
}
